import React from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { Button } from 'antd';
import { useAtom, useAtomValue } from 'jotai';
import { generatePdf } from '@/services/commonService';
import Left from './Left';
import Context from './Context';
import styles from './index.module.less';
import { comDataAtom } from './models';

const Index = () => {
  const [_, restData] = useAtom(comDataAtom);
  const values = useAtomValue(comDataAtom);

  const getPriViewUrl = () => {
    const url = new URLSearchParams();
    url.append('comData', JSON.stringify(values));
    const newUrl = `/demoView?${url.toString()}`;
    console.log(url.toString());
    return newUrl;
  };

  const toPreviewSpa = () => {
    let baseUrl = window.location.href;
    baseUrl = baseUrl.replace('/app/demo', '');
    window.open(baseUrl + getPriViewUrl());
  };

  const toPreviewSSR = () => {
    const url = `http://127.0.0.1:8000${getPriViewUrl()}`;
    window.open(url);
  };

  // 生成pdf
  const savePageToPdf = async () => {
    let baseUrl = window.location.href;
    baseUrl = baseUrl.replace('/app/demo', '');
    const url = baseUrl + getPriViewUrl();
    const res = await generatePdf(url);
    console.log('res', res);
  };

  return (
    <>
      <div>
        <Button onClick={() => restData([])}>清空数据</Button>
        <Button onClick={toPreviewSpa}>预览页面SPA</Button>
        <Button onClick={toPreviewSSR}>预览页面SSR</Button>
        <Button onClick={savePageToPdf}>接口生成PDF</Button>
      </div>
      <div className={styles.header} style={{ padding: 24, background: '#fff' }}>
        <DndProvider backend={HTML5Backend}>
          <Left />
          <Context />
        </DndProvider>
      </div>
    </>
  );
};

export default Index;
